<template>
  <div>
    <a-card class="mt-2">
      <a-button type="primary" class="mb-4" :icon="h(PlusOutlined)" @click="handleAdd">
        添加
      </a-button>
      <a-table
        v-if="showTable"
        default-expand-all-rows
        expandRowByClick
        :columns="columns"
        :data-source="data"
        :loading="tableLoading"
        :row-key="(row) => row.deptId + ''"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'actions'">
            <a-button size="small" type="link" @click.stop="handleAdd(record)">
              <a-tooltip>
                <template #title>添加</template>
                <PlusOutlined />
              </a-tooltip>
            </a-button>
            <a-button size="small" type="link" @click.stop="handleEdit(record)">
              <a-tooltip>
                <template #title>编辑</template>
                <EditOutlined />
              </a-tooltip>
            </a-button>
            <a-button size="small" type="link" danger @click.stop="handleDelete(record)">
              <a-tooltip>
                <template #title>删除</template>
                <DeleteOutlined />
              </a-tooltip>
            </a-button>
          </template>
        </template>
      </a-table>
    </a-card>
    <a-modal v-model:open="showModal" :mask-closable="false" :title="title">
      <a-form
        ref="formRef"
        :model="form"
        :rules="rules"
        :label-col="{ span: 5 }"
        style="padding-top: 20px"
      >
        <a-form-item label="部门名称" name="deptName">
          <a-input
            v-model:value="form.deptName"
            allow-clear
            :maxlength="20"
            show-count
            placeholder="请输入部门名称"
            @pressEnter="handleConfirm"
          />
        </a-form-item>
        <a-form-item label="上级部门" name="parentId">
          <a-tree-select
            v-model:value="form.parentId"
            show-search
            style="width: 100%"
            placeholder="请选择"
            allow-clear
            tree-default-expand-all
            :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
            :tree-data="data"
            :field-names="{
              children: 'children',
              label: 'deptName',
              value: 'deptId',
            }"
            tree-node-filter-prop="deptName"
          />
        </a-form-item>
        <a-form-item label="显示顺序" name="deptSort">
          <a-input-number
            v-model:value="form.deptSort"
            allow-clear
            :precision="0"
            style="width: 100%"
            :max="2147483647"
            :min="-2147483648"
          />
        </a-form-item>
      </a-form>
      <template #footer>
        <a-button type="primary" :loading="formBtnLoading" @click="handleConfirm">提交</a-button>
      </template>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
  import { h, onMounted, reactive, ref } from 'vue';
  import DeptApi from '@/api/DeptApi';
  import { DeleteOutlined, EditOutlined, PlusOutlined } from '@ant-design/icons-vue';
  import { message, Modal } from 'ant-design-vue';
  import { Rule } from 'ant-design-vue/es/form';
  import { resetReactive } from '@/utils';

  let columns = [
    { title: '部门名称', dataIndex: 'deptName' },
    { title: '显示顺序', dataIndex: 'deptSort' },
    { title: '创建时间', dataIndex: 'createTime' },
    { title: '更新时间', dataIndex: 'updateTime' },
    {
      title: '操作',
      dataIndex: 'actions',
      align: 'center',
    },
  ];
  let data = ref([]);
  onMounted(() => {
    getList();
  });

  const tableLoading = ref(false);
  const showTable = ref(false);

  function getList() {
    tableLoading.value = true;
    DeptApi.tree()
      .then((res) => {
        data.value = res.data;
      })
      .finally(() => {
        tableLoading.value = false;
        showTable.value = true;
      });
  }

  const showModal = ref(false);
  const title = ref('');
  const formRef = ref();
  let form = reactive<any>({});
  const rules: Record<string, Rule[]> = {
    deptName: [
      { required: true, trigger: ['blur', 'change'], message: '请输入部门名称' },
      { min: 2, max: 20, message: '长度应为 2 到 20 个字符', trigger: 'change' },
    ],
  };

  function handleEdit(row) {
    showModal.value = true;
    title.value = '编辑';
    Object.assign(form, row);
    formRef.value?.clearValidate();
  }

  function handleAdd(record) {
    showModal.value = true;
    title.value = '添加';
    resetReactive(form);
    record && (form.parentId = record.deptId);
    formRef.value?.clearValidate();
  }

  const formBtnLoading = ref(false);

  function handleConfirm() {
    formRef.value
      .validate()
      .then(() => {
        formBtnLoading.value = true;
        (form.deptId ? DeptApi.update(form) : DeptApi.save(form))
          .then(() => {
            message.success('提交成功');
            showModal.value = false;
            getList();
          })
          .finally(() => {
            formBtnLoading.value = false;
          });
      })
      .catch(() => {});
  }

  function handleDelete(row) {
    Modal.confirm({
      title: '提示',
      content: '确定删除这条记录吗',
      onOk: () => {
        DeptApi.delete([row.deptId]).then(() => {
          message.success('操作成功');
          getList();
        });
      },
      onCancel: () => {},
    });
  }
</script>

<style scoped></style>
